<?php
defined('IN_PHPCMS') or exit('No permission resources.');
pc_base::load_sys_class('model', '', 0);
class access_token_model extends model {

	public $catid = 7;

	function __construct() {
		$this->db_config = pc_base::load_config('database');
		$this->db_setting = 'default';
		$this->table_name = 'access_token';
		parent::__construct();
	}

	/**
	 * 获取 access_token
	 */
	public function get_access_token(int $id)
	{
		$one = $this->get_one(['id'=>$id]);
		$APPID = $one['appid'];
		$APPSECRET = $one['secret'];
		// 有效
		if($one['expires_time'] > date('Y-m-d H:i:s')){
			return $one['access_token'];
		}

		// 无效 重新获取
		$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$APPID&secret=$APPSECRET";
		$content = file_get_contents($url);

		$array = json_decode($content, true);
		$access_token = $array['access_token'];
		$expires_in = $array['expires_in'];

		$expires_time = date('Y-m-d H:i:s', time() + $expires_in);
		$this->update(['access_token'=>$access_token, 'expires_time'=>$expires_time], ['id'=>$id]);

		return $access_token;
	}

	/**
	 * 获取微信二维码
	 * $id 电子报文章 id
	 * $page pages/index/index
	 * $scene eg: a=1&b=2
	 * $env_version trial 体验版 release 开发版
	 */
	public function get_qrcode(int $id, string $page, string $env_version='trial', $cache=true){

		$file_dir = '';
		switch($env_version){
			case 'trial':
				$file_dir = 'uploadfile/epaper_qrcode/trial';
			break;
			case 'release':
				$file_dir = 'uploadfile/epaper_qrcode/release';
			break;
			case 'develop':
				$file_dir = 'uploadfile/epaper_qrcode/develop';
			break;
			default:
				throw new Exception('发生错误！');
		}

		if(!file_exists($file_dir)){
			mkdir($file_dir,0777,true);
		}

		$file_path = $file_dir.'/'.$id.'.png';
		
		if($cache && file_exists($file_path)){
			return file_get_contents($file_path);
		}

		$ACCESS_TOKEN = $this->get_access_token(1);
		$url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=$ACCESS_TOKEN";  //调用接口的平台服务地址

		// 参数
		$data = [
			'page'=>$page,
			'scene'=>'id='.$id,
			'check_path'=>true,
			'width'=>280,
			'env_version'=>$env_version,
			'is_hyaline'=>true,
		];

		// 发送请求
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if(!$data)
			throw new Exception('发生错误 data 无数据');
        if(is_array($data))
            $data = json_encode($data);
		
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_HTTPHEADER, [
                'Content-Type: application/json; charset=utf-8',
                'Content-Length:' . strlen($data),
                'Cache-Control: no-cache',
                'Pragma: no-cache'
        ]);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($curl);
        $errorno = curl_errno($curl);
        if ($errorno)
			throw new Exception('发生错误 errorno：', $errorno);

		$status = curl_getinfo($curl,CURLINFO_HTTP_CODE);

		curl_close($curl);

		if($status != 200){
			throw new Exception('发生错误 http status:'.$status);
		}

		$j = json_decode($res,true);
		if($j){
			throw new Exception('发生错误：'.$res);
		}
		
		file_put_contents($file_path, $res);

		return file_get_contents($file_path);
	}

}